﻿using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour 
{

    public float MaxSpeed = 200f;
    public float SpeedAcceleration = 10f;
    public int MaxHealth = 100;
    public float RotationSmoothness = 10f;

    public Projectile Projectile;
    public Transform ProjectileFireLocation;
    public float FireRate;

    private CharacterController2D _controller;
    private float _normalizedSpeed;
    private float _angleFacing;
    private float _canFireIn;
    private Vector2 _direction;

    public void Awake()
    {
        _controller = GetComponent<CharacterController2D>();
        _angleFacing = 0;
    }

    public void Update()
    {
        _canFireIn -= Time.deltaTime;
         
        HandleInput();

        var targetAngle = 
        transform.rotation = Quaternion.Slerp(
            transform.rotation, 
            Quaternion.Euler(0, 0, _angleFacing),
            Time.deltaTime * RotationSmoothness
            );

        var currentAngle = transform.rotation.eulerAngles.z + 90;

        _direction = new Vector2(
            Mathf.Cos(Mathf.Deg2Rad * currentAngle),
            Mathf.Sin(Mathf.Deg2Rad *currentAngle));

        _controller.SetForce(Vector2.Lerp(_controller.Velocity, _direction * _normalizedSpeed * MaxSpeed, Time.deltaTime * SpeedAcceleration));

    }

    public void HandleInput()
    {
        if (Input.GetKey(KeyCode.D))
        {
            _angleFacing += -5;
        }
        else if (Input.GetKey(KeyCode.A))
        {
            _angleFacing += 5;
        }      

        if (Input.GetKey(KeyCode.W))
        {
            _normalizedSpeed = 1;
        }
        else if (Input.GetKey(KeyCode.S))
        {
            _normalizedSpeed = -1;
        }
        else
        {
            _normalizedSpeed = 0;
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            FireProjectile();
        }

    }

    public void FireProjectile()
    {
        if (_canFireIn > 0)
            return;
        var projectile = (Projectile) Instantiate(Projectile, ProjectileFireLocation.position, transform.rotation);
        projectile.Initialize(gameObject,_direction, _controller.Velocity);

        _canFireIn = FireRate;
    }

    public void Kill()
    {
        collider2D.enabled = false;
        gameObject.SetActive(false);
    }

}
